//home.js
//获取应用实例
var app = getApp();
//缓存当前店铺
var currentShopId = 0;
var defaultImg =  '../../images/default-slide.jpg';
var shareImg = defaultImg;
var currentPage = 1;
    
Page({
  data: {
    loadMore: true,
    hotTitle: '小店优选',
    products: [], 
    status: "",
    history:"../../images/history.png",
    me:"../../images/me.png",
    shop:"../../images/shop_on.png",
    log:"../../images/log-in.png",
    showModal:false,
  },
  onShow: function(){
    var token = wx.getStorageSync('token');
    var session_3rd = wx.getStorageSync('session_3rd');
    if(!token || !session_3rd){
      this.setData({
        showModal:true,
      })
    }
    var that = this;
    //优选标题
    var hTitle = wx.getStorageSync('hot_title');
    if (hTitle && hTitle.length > 0) {
      this.setData({ hotTitle: hTitle });
    }
  },
  onReady: function(){
    var that = this;
    currentPage = 1;

    app.util.appInfo(app, function(res){
      wx.setNavigationBarTitle({
        title: res.result.name,
      });

      if(res.result.share_img.length > 0 ){
        shareImg = res.result.share_img;
      }
      that.setData({
        app_name: res.result.name, 
        is_search:res.result.is_search,
        app_descrip: res.result.descrip,
        app_share_img: shareImg,
        app_link: res.result.link
      });
    });
  },
  other:function(e){
    var appid = e.currentTarget.dataset.appid;
    var link = e.currentTarget.dataset.link;
    wx.navigateToMiniProgram({
      appId: appid,
      path: link,
      extraData: {
      foo: 'wdian' //传递的参数
      },
    envVersion: 'release', //develop（开发版），trial（体验版），release（正式版）
    success(res) {
      console.log(res);
    }
    });
  },
  clickinfo:function(){
    this.setData({
      showModal:false,
    })
  },
  newlogin:function(e){
    if(e.detail.errMsg!='getUserInfo:fail auth deny' && e.detail.userInfo){
      wx.login({
        success: function (res) {
          var nickname = e.detail.userInfo.nickName;
          var avatar = e.detail.userInfo.avatarUrl;    
  

          //授权登录，获取3rd_session
          app.func.req("index/wx_xcx_login", { code: res.code, app_id: app.app_id ,nickname:nickname,avatar:avatar}, "GET", function (res) {
              console.log(res);
              var session_3rd = res.result.session_3rd;
              var token = res.result.token;

              try {
                wx.setStorageSync('token', token);
                wx.setStorageSync('session_3rd', session_3rd);
              } catch (e) {
                console.log(e)
              }


          });
        },
        fail: function () {
          wx.login();
        }
      });
    }
    //app.util.newLogin(app,function(res){});
  },
  onLoad: function (options) {
    currentShopId =  wx.getStorageSync('shop_id');
    var that = this;
    this.getSlides();
    this.getProducts();

    app.func.req('mode/preferred_mode', {}, 'GET', function (res) {
      that.setData({
        list:res.result,
      })
    });
    //识别商品小程序码
    if (options.scene){
      wx.showLoading({
        title: '加载中',
        mask: true
      });

      var productInfo = decodeURIComponent(options.scene)
      productInfo = productInfo.split('-');

      if (productInfo.length > 0) {
        var pid = productInfo[0].split(':')[1];
        var sid = productInfo[1].split(':')[1];
        wx.redirectTo({
          url: '/pages/share/share?product_id=' + pid + '&shop_id=' + sid + '&product_share=true'
        })
      }
    }
    app.util.newLogin(app,function(res){
      if(res=='error'){
        var token = wx.getStorageSync('token');
          if(!token){
            that.setData({
              showModal:true,
          })
        }
      }

      if(res){
        //TODO: 有bug，如果直接扫码进入
        var qrcodeId = wx.getStorageSync('qrcode_id');
        if (qrcodeId) {
          wx.setStorageSync('shop_id', qrcodeId);
          app.func.req("shops/check_shop", {
            id: qrcodeId,
          }, "GET", function (res) {
            wx.removeStorageSync('qrcode_id');
            if (res.code == "success") {
              wx.navigateTo({
                url: '/pages/products/products?shop_id=' + qrcodeId
              });
            }
          }, { token: wx.getStorageSync('token') })

        }

        wx.hideLoading();
      }
    });
  },
  getProducts: function () {
    var that = this;
    that.setData({loadMore: false});
    app.func.req('index/hots', {
      shop_id: currentShopId,
      page_index: currentPage,
      app_id: app.app_id,
      page_size: 20
    }, 'GET', function (res) {
      if (res.code == "success" && res.result.length > 0) {
          console.log(res.result)
          res.result.map(
              (el)=>{
                 if(el.desc.length>20) el.desc=el.desc.substr(0,20)+"...";
              }
          )
        that.setData({
          products: res.result
        });
        currentPage++;
      }
    }, {
        'token': wx.getStorageSync('token')
    });
  },
  getSlides: function(){
    var that = this;
    app.func.req('index/slides', { app_id: app.app_id }, 'GET', function (res) {
      if (res.code == "success" && res.result.length > 0){
        that.setData({
          slides: res.result
        })
      }else{
        that.setData({
          slides: [{
            page: '',
            url: defaultImg
          }]
        });
      }
    }, {
        token: wx.getStorageSync('token')
    })

    // if(currentShopId > 0){
    //   that.setData({
    //     slides: [{
    //       page: '',
    //       url: defaultImg
    //     }]
    //   });
    // }else{
    //   app.func.req('index/slides', { app_id: app.app_id }, 'GET', function (res) {
    //     if (res.code == "success" && res.result.length > 0){
    //       that.setData({
    //         slides: res.result
    //       })
    //     }else{
    //       that.setData({
    //         slides: [{
    //           page: '',
    //           url: defaultImg
    //         }]
    //       });
    //     }
    //   }, {
    //       token: wx.getStorageSync('token')
    //   })
    // }
  },
  scan: function () {
    var that = this;
    wx.scanCode({
      success: function(res){
        var shopId = 0;
        if (res.errMsg == 'scanCode:ok' && res.path != undefined && res.path.length > 0 ) {
          shopId = res.path.split('id=')[1];
        } else {
          shopId = parseInt(res.result);
        }
        app.func.req("shops/check_shop", {
          id: currentShopId,
        }, "GET", function (res) {
          if (res.code == "success") {
            wx.setStorageSync('shop_id', shopId);
            wx.navigateTo({
              url: '/pages/products/products_flex?shop_id=' + shopId
            });
          }
          else {
            wx.showToast({
              title: '店铺暂不可用',
              image: '/images/fail.png',
              duration: 3000
            })
          }
        }, { token: wx.getStorageSync('token') })},
      fail: function(res) {
        //暂时将扫码后店铺不存在放这
        wx.showToast({
          title: '店铺不存在',
          image: '/images/fail.png',
          duration: 3000
        })
      }
    })
  },
  contactUs: function(){
    wx.navigateTo({
      url: '/pages/common/contact'
    });
  },
  onShareAppMessage: function(){
    var that = this;
    var url = wx.getStorageSync('current_index_url');
    if (!url) {
      url = '/pages/load/load';
    }
    return {
      title: this.data.app_descrip,
      path: url
    }
  },
  goCurrentShop: function(){
    var currentShopId =  wx.getStorageSync('current_shop_id');
    if (currentShopId > 0) {
      var currentShopUrl = wx.getStorageSync('current_shop_url');
      app.func.req("shops/check_shop", {
        id: currentShopId,
      }, "GET", function (res) {
        if(res.code == "success") {
          wx.navigateTo({
            url: currentShopUrl + '?shop_id=' + currentShopId + '&share=true'
          });
        }
        else{
          wx.clearStorageSync('current_shop_id')
          wx.showToast({
            title: '该商店暂不可用',
            image: '/images/fail.png',
            duration: 2000
          });
        }
      }, { token: wx.getStorageSync('token') })} else {
      wx.showToast({
        title: '暂无浏览记录',
        image: '/images/fail.png',
        duration: 2000
      });
    }
  }
})
